package AudioUDP.Receiver;


public class FIFO {

	private  byte[] file;
	private int in;
	private int out;
	private int nbelt;
	
	
	public FIFO( int taille){
		in=0;
		out=0;
		nbelt=0;
		file = new byte[taille];
		
	}
	
	public int getNbelt(){
		
		return nbelt;
	}
	
	public boolean equals(FIFO f)  {
		if (!(this.file.length == f.file.length)) return false;
		if (!(this.nbelt == f.nbelt)) return false;
		int[] thisFile , fFile;
		thisFile= this.parcours();
		fFile=f.parcours();
		for ( int i=0; i<= thisFile.length-1;i++)	if(thisFile[i]!= fFile[i]) return false;
		return true;
	}
	
	public int[] parcours(){
		int retour[] = new int[this.nbelt];
		if (this.estVide())	return retour;
		int i=0;
		int incrThis = this.out;
		for ( ; i < this.nbelt;i++){
			if (incrThis == this.file.length) incrThis = 0;
			retour[i]= this.file[incrThis];
			incrThis++;
		}		
		return retour;						
	}
	
	public int compare(FIFO f){
		if (this.nbelt>f.nbelt)return (-1);
		if (this.nbelt==f.nbelt)return 0;
		return 1;
	}
	
	public String toString(){
		StringBuffer chaine = new StringBuffer();
		int[] f= this.parcours();
		chaine.append("taille: "+this.file.length+", nombre d'éléments: "+this.nbelt+", contenu de la file : ");
		for(int i=0;i<f.length;++i){
			chaine.append(f[i]).append(" ");
			
		}
		
		return chaine.substring(0);
	}
	
	private boolean estVide(){
		
		return nbelt == 0;
	}
	
	private boolean estPleine(){

		return nbelt == this.file.length;
	}
	
	synchronized public void entrer(byte e) throws InterruptedException{
		notifyAll();
		while(this.estPleine())
			wait();

		this.file[in] = e;
		this.nbelt++;
		this.in ++;
		if (this.in == this.file.length) in = 0;	
		return;	
	}
	
	synchronized public byte sortir()throws InterruptedException{
		byte temp; 
		notifyAll();
		while(this.estVide())
			wait();
		
	
		temp = this.file[out];
		this.nbelt--;
		this.out++;
		if (this.out == this.file.length-1 || this.out == -1) this.out = 0;
		return temp;
	
	}
	

}
